package com.un.ebs.customer.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.un.ebs.core.common.GroupInfo;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import com.un.ebs.customer.CustomerConfigureCode;
import com.un.ebs.customer.domain.Customer;
import com.un.ebs.customer.domain.CustomerAndDefunctExt;
import com.un.ebs.customer.domain.CustomerExt;
import com.un.ebs.customer.dto.CustomerAddBySuggestDto;
import com.un.ebs.customer.dto.CustomerAddDto;
import com.un.ebs.customer.dto.CustomerRealNameBindRequest;
import com.un.ebs.customer.dto.CustomerUpdateDto;
import com.un.ebs.customer.enums.CustomerStatusEnum;
import com.un.ebs.customer.mapper.CustomerExtMapper;
import com.un.ebs.customer.service.CustomerService;
import com.un.ebs.customer.service.CustomerTraceService;
import com.un.ebs.customer.vo.CustomerDetailVo;
import com.un.ebs.finance.WebService1;
import com.un.ebs.finance.WebService1Soap;
import com.un.ebs.finance.dto.CustomerDto;
import com.un.ebs.order.OrderConfigureCode;
import com.un.ebs.sys.dto.AddressDto;
import com.un.ebs.sys.service.ConfigureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.jasperreports.engine.export.JsonExporter;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-24
 */
@RestController
@RequestMapping("/customer")
@Api(value = "customer")
public class CustomerController {

    @Autowired
    private CustomerService service;

    @Autowired
    private CustomerTraceService customerTraceService;

    @Resource
    private ConfigureService configureService;

    @Autowired
    private CustomerExtMapper customerExtMapper;

    @PostMapping("add")
    @ApiOperation(value = "添加", notes = "添加")
    public WebResult save(@RequestBody @Validated CustomerAddDto req) {
        return WebUtils.success(service.add(req));
    }

    @PostMapping("addBySuggest")
    @ApiOperation(value = "添加，转介绍", notes = "添加")
    public WebResult suggest(@RequestBody @Validated CustomerAddBySuggestDto req) {
        return WebUtils.success(service.add(req));
    }

    @PostMapping("test")
    @ApiOperation(value = "TEST")
    public WebResult test(){

        String url = StringUtils.valueReplace(configureService.getValueByCode(OrderConfigureCode.order_accept_notify_templete_url), "\\{", "\\}", SecurityUtils.getUserContent());
        return WebUtils.success(url);
    }

    @PostMapping("update")
    @ApiOperation(value = "修改", notes = "修改")
    public WebResult update(@RequestBody @Validated CustomerUpdateDto req) {
        service.update(req);
        return WebUtils.success();
    }

    @PostMapping("updateRealName")
    @ApiOperation("微信用户实名绑定")
    public WebResult updateByRealName(@RequestBody @Validated CustomerRealNameBindRequest req) {
        service.update(req);
        return WebUtils.success();
    }

    @PostMapping("changePersonnel")
    @ApiOperation(value = "变更客户的负责人", notes = "变更客户的负责人")
    public WebResult changePersonnel(@RequestParam @ApiParam("客户ID") String custId, @RequestParam String personnelId, @RequestParam(required = false) String remark) {
        service.changePersonnel(custId, personnelId, remark);
        return WebUtils.success();
    }

    @PostMapping("changePersonnelByAvg")
    @ApiOperation(value = "变更客户的负责人", notes = "将指定业务员名下的所有客户，平均分给指定的业务员。")
    public WebResult changePersonnel(@RequestParam @Param("原业务员") String personnelId, @RequestParam(required = false) @Param("新业务员") List<String> toPersonnelIds) {
        service.changePersonnel(personnelId, toPersonnelIds);
        return WebUtils.success();
    }

    @PostMapping("changeLevel")
    @ApiOperation(value = "变更客户级别", notes = "变更客户级别")
    public WebResult changeLevel(@RequestParam String custId, @RequestParam String levelDict, @RequestParam(required = false) String remark) {
        service.changeLevel(custId, levelDict, remark);
        return WebUtils.success();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据主键获取单个 Customer", notes = "根据主键获取单个 Customer")
    public WebResult<CustomerExt> getById(@PathVariable("id") String id) {
        return WebUtils.success(customerExtMapper.selectById(id));
    }

    @GetMapping("queryMobile")
    @ApiOperation(value = "查询客户的手机号码", notes = "查询客户的手机号码")
    public WebResult queryMobile(@RequestParam String id) {
        return WebUtils.success(service.queryMobile(id));
    }

    @GetMapping("detail/{id}")
    @ApiOperation(value = "根据主键获取单个 Customer", notes = "根据主键获取单个 Customer")
    public WebResult<CustomerDetailVo> getViewById(@PathVariable("id") String id) {
        CustomerDetailVo result = new CustomerDetailVo();
        CustomerExt customer = service.queryViewById(id);
        if (customer == null) {
            throw new BusinessEntityNotFoundException(id, "客户");
        }
        BeanUtils.copyProperties(customer, result);

        result.setTraceList(customerTraceService.queryByCustId(id));
        result.setOrderList(service.queryOrderByCustId(id));

        return WebUtils.success(result);
    }

    @GetMapping("list")
    @ApiOperation(value = "查询客户", notes = "")
    public WebResult<IPage<CustomerExt>> list(@RequestParam(required = false) String searchText,
                                              @RequestParam(required = false) String personnelId,
                                              @RequestParam(required = false) CustomerStatusEnum status,
                                              @RequestParam int pageSize,
                                              @RequestParam int pageIndex) {
        return WebUtils.success(service.query(searchText, personnelId, status, pageSize, pageIndex));
    }

    @GetMapping("listMyCustomer")
    @ApiOperation(value = "查询当前用户所关联的客户列表", notes = "查询当前用户所关联的客户列表")
    public WebResult<List<CustomerExt>> listMyCustomer() {
        return WebUtils.success(service.queryViewByUserId(SecurityUtils.getUserContent().getId()));
    }

    @GetMapping("currentCustomer")
    @ApiOperation(value = "当前用户关联的客户")
    public WebResult<Customer> queryCurrent() {
        return WebUtils.success(service.queryCurrent());
    }

    @GetMapping("currentDefunct")
    @ApiOperation(value = "当前用户关联的客户和逝者")
    public WebResult<CustomerAndDefunctExt> queryCurrentDefunct() {
        return WebUtils.success(service.queryCurrentCustomerAndDefunct());
    }

    @GetMapping("listAddrs")
    @ApiOperation("获取当前客户的通讯地址列表")
    public WebResult<List<AddressDto>> listAddrs(@RequestParam(required = false) String skuId) {
        // TODO: 2020/3/8 需按SPU配置损赠对象
        if ("043929c7c4de1bb1333806977bfe18b5".equals(skuId) || "5d9678b033ee70907a23ff35e12fcaa7".equals(skuId)) {
            System.out.println("sku id : " + skuId);
            List<AddressDto> result = new ArrayList<>();
            result.add(new AddressDto("长沙市各大医院", "13607316978", "湖南省，长沙市"));
            return WebUtils.success(result);
        }
        if (SecurityUtils.getUserContent() != null) {
            return WebUtils.success(service.queryAddrByUserId(SecurityUtils.getUserContent().getId()));
        } else {
            throw new BusinessException("当前用户信息不能为空。");
        }
    }

    @GetMapping("listStatusCount")
    @ApiOperation(value = "查询不同状态下的客户数量", notes = "")
    public WebResult<List<GroupInfo>> listStatusCount() {
        List<GroupInfo> result = new ArrayList<>();
        LambdaQueryWrapper<CustomerExt> queryIntent = Wrappers.lambdaQuery();
        queryIntent.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        queryIntent.eq(CustomerExt::getCustStatus, CustomerStatusEnum.Intent);

        if (!service.hasQueryAllPower()) {
            queryIntent.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        }
        result.add(new GroupInfo(String.valueOf(CustomerStatusEnum.Intent.getCode()), CustomerStatusEnum.Intent.getDesc(), customerExtMapper.selectCount(queryIntent), CustomerStatusEnum.Intent.toString()));

        LambdaQueryWrapper<CustomerExt> queryOrder = Wrappers.lambdaQuery();
        queryOrder.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        queryOrder.eq(CustomerExt::getCustStatus, CustomerStatusEnum.Order);
        if (!service.hasQueryAllPower()) {
            queryOrder.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        }
        result.add(new GroupInfo(String.valueOf(CustomerStatusEnum.Order.getCode()), CustomerStatusEnum.Order.getDesc(), customerExtMapper.selectCount(queryOrder), CustomerStatusEnum.Order.toString()));

        LambdaQueryWrapper<CustomerExt> queryDeliver = Wrappers.lambdaQuery();
        queryDeliver.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        queryDeliver.eq(CustomerExt::getCustStatus, CustomerStatusEnum.Deliver);
        if (!service.hasQueryAllPower()) {
            queryDeliver.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
        }
        result.add(new GroupInfo(String.valueOf(CustomerStatusEnum.Deliver.getCode()), CustomerStatusEnum.Deliver.getDesc(), customerExtMapper.selectCount(queryDeliver), CustomerStatusEnum.Deliver.toString()));
        return WebUtils.success(result);
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "根据主键删除单个 Customer", notes = "根据主键删除单个 Customer")
    public WebResult delete(@PathVariable("id") String id) {
        service.delete(id);
        return WebUtils.success();
    }

    @GetMapping("queryBind")
    @ApiOperation(value = "查询客户与逝者的绑定信息", notes = "一般有过订单的会自动建立绑定信息，支持客户名称、手机号码、逝者名称查询")
    public WebResult<List<CustomerAndDefunctExt>> queryBind(@RequestParam String entId, @RequestParam String searchText) {
        if (StringUtils.isNullOrEmpty(searchText)) {
            throw new BusinessException("查询内容不能为空。");
        }
        if (StringUtils.isNumeric(searchText) && searchText.length() < 8) {
            throw new BusinessException("手机号码查询不能少于8位数字");
        } else if (searchText.length() < 2) {
            throw new BusinessException("查询内容至少是2个汉字。");
        }
        return WebUtils.success(service.queryBindList(entId, searchText));
    }

    @PostMapping("createToUser")
    @ApiOperation(value = "客户绑定到用户", notes = "")
    public WebResult createToUser(@RequestParam String id, @RequestParam String openId) {
        service.bindToUser(id, openId);
        return WebUtils.success();
    }

}